<template>
  <view class="page-container">
    <view v-if="loading" class="loading-container">
      <uni-load-more status="loading"></uni-load-more>
    </view>
    
    <view v-else-if="verifyDetail" class="detail-container">
      <!-- 核销状态卡片 -->
      <view class="status-card">
        <view class="status-icon" :class="getStatusClass(verifyDetail.status)">
          <uni-icons 
            :type="getStatusIcon(verifyDetail.status)" 
            size="32" 
            color="#fff"
          ></uni-icons>
        </view>
        <view class="status-info">
          <text class="status-text">{{ getVerifyStatusText(verifyDetail.status) }}</text>
          <text class="status-time">{{ formatTime(verifyDetail.created_at) }}</text>
        </view>
      </view>

      <!-- 优惠券信息 -->
      <view class="info-section">
        <view class="section-title">优惠券信息</view>
        <view class="info-card">
          <view class="info-row">
            <text class="label">优惠券名称</text>
            <text class="value">{{ verifyDetail.coupon_name }}</text>
          </view>
          <view class="info-row">
            <text class="label">优惠券码</text>
            <text class="value code-text">{{ verifyDetail.coupon_code }}</text>
          </view>
          <view class="info-row">
            <text class="label">优惠券类型</text>
            <text class="value">{{ getCouponTypeText(verifyDetail.coupon_type) }}</text>
          </view>
          <view class="info-row">
            <text class="label">优惠金额</text>
            <text class="value amount-text">¥{{ (verifyDetail.discount_amount || 0) / 100 }}</text>
          </view>
        </view>
      </view>

      <!-- 核销信息 -->
      <view class="info-section">
        <view class="section-title">核销信息</view>
        <view class="info-card">
          <view class="info-row">
            <text class="label">核销员</text>
            <text class="value">{{ verifyDetail.verifier_name || '系统自动' }}</text>
          </view>
          <view class="info-row">
            <text class="label">核销时间</text>
            <text class="value">{{ formatDetailTime(verifyDetail.created_at) }}</text>
          </view>
          <view class="info-row" v-if="verifyDetail.order_no">
            <text class="label">关联订单</text>
            <text class="value order-text" @click="goToOrder(verifyDetail.order_no)">
              {{ verifyDetail.order_no }}
            </text>
          </view>
          <view class="info-row" v-if="verifyDetail.store_name">
            <text class="label">核销门店</text>
            <text class="value">{{ verifyDetail.store_name }}</text>
          </view>
        </view>
      </view>

      <!-- 用户信息 -->
      <view class="info-section" v-if="verifyDetail.user_info">
        <view class="section-title">用户信息</view>
        <view class="info-card">
          <view class="info-row">
            <text class="label">用户昵称</text>
            <text class="value">{{ verifyDetail.user_info.nickname || '未知用户' }}</text>
          </view>
          <view class="info-row">
            <text class="label">手机号码</text>
            <text class="value">{{ verifyDetail.user_info.phone || '未绑定' }}</text>
          </view>
          <view class="info-row">
            <text class="label">会员等级</text>
            <text class="value">{{ getMemberLevelText(verifyDetail.user_info.member_level) }}</text>
          </view>
        </view>
      </view>

      <!-- 备注信息 -->
      <view class="info-section" v-if="verifyDetail.remark">
        <view class="section-title">备注信息</view>
        <view class="info-card">
          <text class="remark-text">{{ verifyDetail.remark }}</text>
        </view>
      </view>

      <!-- 失败原因 -->
      <view class="info-section" v-if="verifyDetail.status === 0 && verifyDetail.error_message">
        <view class="section-title">失败原因</view>
        <view class="info-card error-card">
          <uni-icons type="info" size="16" color="#ff4d4f"></uni-icons>
          <text class="error-text">{{ verifyDetail.error_message }}</text>
        </view>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="bottom-actions" v-if="verifyDetail && verifyDetail.status === 2">
      <button class="action-btn reject-btn" @click="handleReject">拒绝</button>
      <button class="action-btn approve-btn" @click="handleApprove" :loading="processing">通过</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { fetchVerifyDetail } from '@/api/coupon';
import { getCouponTypeText } from '@/utils/coupon';
import moment from 'moment';

interface VerifyDetail {
  id: number;
  coupon_id: number;
  coupon_name: string;
  coupon_code: string;
  coupon_type: number;
  status: number; // 0: 失败, 1: 成功, 2: 待处理
  verifier_id?: number;
  verifier_name?: string;
  discount_amount?: number;
  order_no?: string;
  store_name?: string;
  user_info?: {
    nickname?: string;
    phone?: string;
    member_level?: number;
  };
  remark?: string;
  error_message?: string;
  created_at: number;
  updated_at: number;
}

const verifyDetail = ref<VerifyDetail | null>(null);
const loading = ref(true);
const processing = ref(false);
const verifyId = ref<number | null>(null);

const getVerifyDetail = async (id: number) => {
  try {
    loading.value = true;
    const res = await fetchVerifyDetail(id);
    verifyDetail.value = res;
  } catch (error) {
    console.error('获取核销详情失败:', error);
    uni.showToast({
      title: '获取详情失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

const getVerifyStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    1: '核销成功',
    0: '核销失败',
    2: '待处理'
  };
  return statusMap[status] || '未知状态';
};

const getStatusClass = (status: number) => {
  const classMap: Record<number, string> = {
    1: 'success',
    0: 'error',
    2: 'warning'
  };
  return classMap[status] || 'default';
};

const getStatusIcon = (status: number) => {
  const iconMap: Record<number, string> = {
    1: 'checkmarkempty',
    0: 'closeempty',
    2: 'clock'
  };
  return iconMap[status] || 'help';
};

const getMemberLevelText = (level?: number) => {
  const levelMap: Record<number, string> = {
    1: '普通会员',
    2: '银卡会员',
    3: '金卡会员',
    4: 'VIP会员'
  };
  return level ? levelMap[level] || '未知等级' : '非会员';
};

const formatTime = (timestamp: number) => {
  return moment(timestamp * 1000).format('MM-DD HH:mm');
};

const formatDetailTime = (timestamp: number) => {
  return moment(timestamp * 1000).format('YYYY-MM-DD HH:mm:ss');
};

const goToOrder = (orderNo: string) => {
  uni.navigateTo({
    url: `/pages/orders/detail?orderNo=${orderNo}`
  });
};

const handleApprove = async () => {
  if (!verifyId.value) return;
  
  uni.showModal({
    title: '确认操作',
    content: '确定要通过此核销申请吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          processing.value = true;
          // 这里应该调用审批API
          // await approveVerify(verifyId.value, { status: 1 });
          
          uni.showToast({
            title: '操作成功',
            icon: 'success'
          });
          
          // 刷新详情
          await getVerifyDetail(verifyId.value!);
        } catch (error) {
          console.error('操作失败:', error);
          uni.showToast({
            title: '操作失败',
            icon: 'none'
          });
        } finally {
          processing.value = false;
        }
      }
    }
  });
};

const handleReject = () => {
  if (!verifyId.value) return;
  
  uni.showModal({
    title: '拒绝核销',
    editable: true,
    placeholderText: '请输入拒绝原因',
    success: async (res) => {
      if (res.confirm) {
        try {
          processing.value = true;
          // 这里应该调用拒绝API
          // await rejectVerify(verifyId.value, { 
          //   status: 0, 
          //   error_message: res.content || '管理员拒绝' 
          // });
          
          uni.showToast({
            title: '操作成功',
            icon: 'success'
          });
          
          // 刷新详情
          await getVerifyDetail(verifyId.value!);
        } catch (error) {
          console.error('操作失败:', error);
          uni.showToast({
            title: '操作失败',
            icon: 'none'
          });
        } finally {
          processing.value = false;
        }
      }
    }
  });
};

onLoad((options: any) => {
  if (options.id) {
    verifyId.value = Number(options.id);
    getVerifyDetail(verifyId.value);
  }
});
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background-color: var(--background-color);
  padding-bottom: 80px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.detail-container {
  padding: 15px;
}

.status-card {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: var(--border-radius-lg);
  padding: 20px;
  margin-bottom: 15px;
  box-shadow: var(--shadow);
  
  .status-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;
    
    &.success {
      background-color: #52c41a;
    }
    
    &.error {
      background-color: #ff4d4f;
    }
    
    &.warning {
      background-color: #faad14;
    }
    
    &.default {
      background-color: #d9d9d9;
    }
  }
  
  .status-info {
    flex: 1;
    
    .status-text {
      display: block;
      font-size: 18px;
      font-weight: bold;
      color: var(--text-color-primary);
      margin-bottom: 5px;
    }
    
    .status-time {
      font-size: 12px;
      color: var(--text-color-secondary);
    }
  }
}

.info-section {
  margin-bottom: 15px;
  
  .section-title {
    font-size: 16px;
    font-weight: bold;
    color: var(--text-color-primary);
    margin-bottom: 10px;
    padding-left: 5px;
  }
}

.info-card {
  background-color: #fff;
  border-radius: var(--border-radius);
  padding: 15px;
  box-shadow: var(--shadow);
  
  &.error-card {
    display: flex;
    align-items: flex-start;
    background-color: #fff2f0;
    border: 1px solid #ffccc7;
    
    .error-text {
      margin-left: 8px;
      color: #ff4d4f;
      font-size: 14px;
      line-height: 1.5;
    }
  }
  
  .info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid var(--border-color);
    
    &:last-child {
      border-bottom: none;
    }
    
    .label {
      font-size: 14px;
      color: var(--text-color-secondary);
      min-width: 80px;
    }
    
    .value {
      font-size: 14px;
      color: var(--text-color-primary);
      text-align: right;
      flex: 1;
      
      &.code-text {
        font-family: 'Courier New', monospace;
        background-color: var(--background-color);
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
      }
      
      &.amount-text {
        color: var(--primary-color);
        font-weight: bold;
        font-size: 16px;
      }
      
      &.order-text {
        color: var(--primary-color);
        text-decoration: underline;
      }
    }
  }
  
  .remark-text {
    font-size: 14px;
    color: var(--text-color-primary);
    line-height: 1.6;
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 15px;
  background-color: #fff;
  border-top: 1px solid var(--border-color);
  gap: 15px;
  
  .action-btn {
    flex: 1;
    height: 44px;
    border-radius: var(--border-radius);
    font-size: 16px;
    border: none;
    
    &.reject-btn {
      background-color: #ff4d4f;
      color: #fff;
    }
    
    &.approve-btn {
      background-color: #52c41a;
      color: #fff;
    }
  }
}
</style>